package com.ruoyi.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.customer.domain.Customer;
import com.ruoyi.customer.domain.TRevieweInfo;
import com.ruoyi.customer.domain.bo.CustomerBo;
import com.ruoyi.customer.domain.bo.TRevieweBo;
import com.ruoyi.customer.domain.bo.TRevieweInfoBo;
import com.ruoyi.customer.domain.bo.WithdrawBo;
import com.ruoyi.customer.domain.vo.CustomerVo;
import com.ruoyi.customer.domain.vo.TRevieweInfoVo;
import com.ruoyi.customer.domain.vo.TRevieweVo;
import com.ruoyi.customer.domain.vo.WithdrawInfoVo;
import com.ruoyi.customer.mapper.CustomerMapper;
import com.ruoyi.customer.mapper.TCustomerTaskMapper;
import com.ruoyi.customer.mapper.TRevieweInfoMapper;
import com.ruoyi.customer.service.ITRevieweCooperateService;
import com.ruoyi.customer.service.ITRevieweInfoService;
import com.ruoyi.disCustomer.domain.TCustomerDisRecord;
import com.ruoyi.disCustomer.mapper.TCustomerDisRecordMapper;
import com.ruoyi.enums.BusTypeEnum;
import com.ruoyi.enums.CompanyStatusEnum;
import com.ruoyi.enums.CustomerStatusEnum;
import com.ruoyi.system.domain.TFileInfo;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysRegionService;
import com.ruoyi.system.service.ITFileInfoService;
import com.ruoyi.teamCustomer.mapper.TeamCustomerMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 再审件Service业务层处理
 *
 * @author zr
 * @date 2023-08-02
 */
@RequiredArgsConstructor
@Service
public class TRevieweInfoServiceImpl implements ITRevieweInfoService {

    private final TRevieweInfoMapper baseMapper;
    private final ITFileInfoService fileInfoService;
    private final CustomerMapper customerMapper;
    private final TeamCustomerMapper teamCustomerMapper;
    private final TCustomerDisRecordMapper disRecordMapper;
    private final ISysRegionService sysRegionService;
    private final CustomerServiceImpl customerServiceImpl;
    private final TCustomerTaskMapper taskMapper;
    private final ISysConfigService sysConfigService;
    private final ITRevieweCooperateService cooperateService;

    /**
     * 查询再审件
     */
    @Override
    public TRevieweInfoVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询再审件列表
     */
    @Override
    public TableDataInfo<TRevieweInfoVo> queryPageList(TRevieweInfoBo bo, PageQuery pageQuery) {
        Page<TRevieweInfoVo> result = baseMapper.selectPageRevieweList(pageQuery.build(), this.buildWrapper(bo));
        return TableDataInfo.build(result);
    }

    /**
     * 查询再审件列表
     */
    @Override
    public List<TRevieweInfoVo> queryList(TRevieweInfoBo bo) {
        return baseMapper.selectVoList(this.buildWrapper(bo));
    }

    private Wrapper<TRevieweInfo> buildWrapper(TRevieweInfoBo bo) {
        QueryWrapper<TRevieweInfo> query = Wrappers.query();
        query.eq("r.del_flag", UserConstants.USER_NORMAL);
        query.like(StringUtils.isNotBlank(bo.getCustomerName()), "r.customer_name", bo.getCustomerName());
        query.like(StringUtils.isNotBlank(bo.getUserName()), "r.user_name", bo.getUserName());
        query.eq(bo.getDeptId() != null, "r.dept_id", bo.getDeptId());
        query.eq(bo.getUserId() != null, "r.user_id", bo.getUserId());
        query.like(StringUtils.isNotBlank(bo.getContractNum()), "r.contract_num", bo.getContractNum());
        query.eq(StringUtils.isNotBlank(bo.getInBank()), "r.is_bank", bo.getInBank());
        query.eq(bo.getInTime() != null, "r.in_time", bo.getInTime());
        query.eq(bo.getApproveTime() != null, "r.approve_time", bo.getApproveTime());
        query.like(StringUtils.isNotBlank(bo.getChannelManage()), "r.channel_manage", bo.getChannelManage());
        query.eq(StringUtils.isNotBlank(bo.getRevieweStatus()), "r.reviewe_status", bo.getRevieweStatus());

        // 部门信息处理
        if (!LoginHelper.isAdmin(LoginHelper.getUserId())) {
            List<String> stringList = teamCustomerMapper.atDeptLower(LoginHelper.getDeptId());
            // 查找上级部门id
            if (!CollectionUtils.isEmpty(stringList)) {
                query.apply("( r.dept_id in (" + String.join(",", stringList) + ") or r.create_id ="
                        + LoginHelper.getUserId() + ")");
            } else {
                query.apply("r.create_id =" + LoginHelper.getUserId());
            }
        }
        return query;
    }

    /**
     * 新增再审件
     */
    @Override
    @Transactional
    public Boolean insertByBo(TRevieweInfoBo bo) {
        TRevieweInfo add = BeanUtil.toBean(bo, TRevieweInfo.class);
        validEntityBeforeSave(add);
        add.setCreateId(LoginHelper.getUserId());
        add.setUserId(LoginHelper.getUserId());
        add.setUserName(LoginHelper.getLoginUser().getNickName());
        add.setDeptId(LoginHelper.getDeptId());
        add.setRevieweStatus(CustomerStatusEnum.YQY.getCode());

        // 如果客户已经存在再审件记录  不允许添加
        LambdaQueryWrapper<TRevieweInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TRevieweInfo::getDelFlag, "0");
        queryWrapper.notIn(TRevieweInfo::getRevieweStatus, CustomerStatusEnum.YJJ.getCode(), CustomerStatusEnum.YSK.getCode());
        queryWrapper.eq(TRevieweInfo::getCustomerId, bo.getCustomerId());
        // 个人可以重复添加
        queryWrapper.ne(TRevieweInfo::getUserId, LoginHelper.getUserId());
        Long aLong = baseMapper.selectCount(queryWrapper);
        if (aLong > 0) {
            throw new ServiceException("已经存在再审件记录，不可以重复添加");
        }
        if (CollectionUtils.isEmpty(bo.getHtList())) {
            throw new BaseException("文件没有上传");
        } else {
            List<TFileInfo> collect = bo.getHtList().stream().filter(it -> !Objects.equals("1", it.getDelFlag()))
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(collect)) {
                throw new BaseException("文件没有上传");
            }
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            CustomerVo customerVo = Optional.ofNullable(customerMapper.selectVoById(bo.getCustomerId()))
                    .orElseThrow(() -> new ServiceException("客户信息不存在"));
            if (Objects.equals("1", customerVo.getDeleted())) {
                throw new ServiceException("客户信息已经删除");
            }
            // 更新客户审件标识
            Customer customer = new Customer();
            customer.setId(bo.getCustomerId());
            // 更改部门到自己部门
            customer.setCustomerStatus(CustomerStatusEnum.DQY.getCode());
            customer.setDistributeDeptId(LoginHelper.getDeptId());
            customer.setIsReviewe(add.getId());
            customer.setTaskId(LoginHelper.getUserId());
            customer.setCompanyStatus(CompanyStatusEnum.YRL.getCode());
            customer.setLastRemarkTime(DateUtils.getNowDate());
            customerMapper.updateById(customer);

            // 保存文件信息
            fileInfoService.fileList(String.valueOf(add.getId()), "reviewe-file", bo.getHtList());

            // 保存合作单信息
            cooperateService.saveByBoList(add.getId(), bo.getDisType(), LoginHelper.getUserId(), LoginHelper.getDeptId(), add.getRevenue(), bo.getCooperateList());
            TCustomerDisRecord disRecord = new TCustomerDisRecord();
            disRecord.setBusType(BusTypeEnum.ZSJ.getCode());
            disRecord.setCustomerId(bo.getCustomerId());
            disRecord.setDisUserId(LoginHelper.getUserId());
            // 分配给哪个部门
            disRecord.setDisDeptId(LoginHelper.getDeptId());
            disRecord.setCustomerName(customerVo.getName());
            disRecord.setTel(customerVo.getTel());
            disRecord.setDisName(LoginHelper.getLoginUser().getDeptName());
            // 记录分配记录
            disRecord(disRecord);
        }
        return flag;
    }

    /**
     * 记录分配记录
     *
     * @param disRecord
     */
    private void disRecord(TCustomerDisRecord disRecord) {
        disRecord.setOperateDisId(LoginHelper.getUserId());
        disRecord.setOperateDeptId(LoginHelper.getDeptId());
        disRecord.setOperateDisName(LoginHelper.getLoginUser().getNickName());
        disRecord.setCreateTime(DateUtils.getNowDate());
        disRecordMapper.insert(disRecord);
    }

    /**
     * 修改再审件
     */
    @Override
    public Boolean updateByBo(TRevieweInfoBo bo) {
        TRevieweInfo update = BeanUtil.toBean(bo, TRevieweInfo.class);
        validEntityBeforeSave(update);
        // 已收款和已拒绝客户
        String operationType = bo.getOperationType();
        // 同步更新客户状态
        Customer customer = new Customer();
        customer.setId(bo.getCustomerId());
        customer.setUpdateTime(DateUtils.getNowDate());
        // 是否需要更新客户表
        boolean flag = false;

        // 列表审核、放款、收款按钮操作
        if (StringUtils.isNotBlank(operationType)) {
            // 审批
            if (Objects.equals(operationType, "audit")) {
                update.setRevieweStatus(bo.getRevieweStatus());
                // 操作已拒绝  去除在审件标记
                if (Objects.equals(CustomerStatusEnum.YJJ.getCode(), bo.getRevieweStatus())) {
                    // 查询当前相同客户+用户是否还存在再审件记录
                    LambdaQueryWrapper<TRevieweInfo> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(TRevieweInfo::getDelFlag, "0");
                    queryWrapper.eq(TRevieweInfo::getCustomerId, bo.getCustomerId());
                    // 个人可以重复添加
                    queryWrapper.eq(TRevieweInfo::getUserId, bo.getUserId());
                    queryWrapper.notIn(TRevieweInfo::getRevieweStatus, CustomerStatusEnum.YJJ.getCode(), CustomerStatusEnum.YSK.getCode());
                    // 排除自己
                    queryWrapper.ne(TRevieweInfo::getId, bo.getId());
                    Long aLong = baseMapper.selectCount(queryWrapper);
                    if (aLong > 0) {
                    } else {
                        customer.setIsReviewe(-1L);
                        flag = true;
                    }
                    //customer.setCustomerStatus(bo.getRevieweStatus());
                }
                // 记录审批人、时间
                update.setCheckBy(LoginHelper.getLoginUser().getNickName());
                update.setCheckTime(DateUtils.getNowDate());
            }
            // 放款
            if (Objects.equals(operationType, "loan")) {
                update.setRevieweStatus(CustomerStatusEnum.YFK.getCode());
                // 同步更新客户状态
                //customer.setCustomerStatus(CustomerStatusEnum.YFK.getCode());
            }
            // 收款
            if (Objects.equals(operationType, "retuenMoney")) {
                update.setRevieweStatus(CustomerStatusEnum.YSK.getCode());

                // 查询当前相同客户+用户是否还存在再审件记录
                LambdaQueryWrapper<TRevieweInfo> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(TRevieweInfo::getDelFlag, "0");
                queryWrapper.eq(TRevieweInfo::getCustomerId, bo.getCustomerId());
                // 个人可以重复添加
                queryWrapper.eq(TRevieweInfo::getUserId, bo.getUserId());
                queryWrapper.notIn(TRevieweInfo::getRevieweStatus, CustomerStatusEnum.YJJ.getCode(), CustomerStatusEnum.YSK.getCode());
                // 排除自己
                queryWrapper.ne(TRevieweInfo::getId, bo.getId());
                Long aLong = baseMapper.selectCount(queryWrapper);
                if (aLong > 0) {
                } else {
                    customer.setIsReviewe(-1L);
                    flag = true;
                }
            }
        }

        // 保存备注信息
        customerServiceImpl.saveRemark(bo.getBz(), bo.getCustomerId());
        if (StringUtils.isNotBlank(bo.getBz())) {
            StringBuilder stringBuilder = new StringBuilder();
            String remarkInfo =
                    bo.getBz() + "--" + LoginHelper.getLoginUser().getNickName() + "[" + DateUtils.parseDateToStr(
                            DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()) + "]";
            stringBuilder.append(remarkInfo);
            stringBuilder.append("<br/>");
            if (StringUtils.isNotBlank(bo.getRemark())) {
                stringBuilder.append(bo.getRemark());
            }
            customer.setBz(stringBuilder.toString());
            customer.setLastRemarkTime(DateUtils.getNowDate());
            flag = true;
        }
        if (flag) {
            customerMapper.updateById(customer);
        }
        // 保存文件信息
        fileInfoService.fileList(String.valueOf(bo.getId()), "reviewe-file", bo.getHtList());
        update.setRemark("");

        // 保存合作单信息
        cooperateService.saveByBoList(bo.getId(), bo.getDisType(), bo.getUserId(), bo.getDeptId(), bo.getRevenue(), bo.getCooperateList());
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TRevieweInfo entity) {
        //TODO 做一些数据校验,如唯一约束
//        LambdaQueryWrapper<TRevieweInfo> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(TRevieweInfo::getDelFlag, "0");
//        queryWrapper.eq(TRevieweInfo::getCustomerId, entity.getCustomerId());
//        queryWrapper.eq(TRevieweInfo::getTaskId, entity.getTaskId());
//        queryWrapper.ne(entity.getId() != null, TRevieweInfo::getId, entity.getId());
//        Long count = baseMapper.selectCount(queryWrapper);
//        if (count > 0) {
//            throw new ServiceException("该客户已经存在审计记录!");
//        }
    }

    /**
     * 批量删除再审件
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    /**
     * 在审计列表信息
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<TRevieweVo> queryPageCustomerList(TRevieweBo bo, PageQuery pageQuery) {
        Page<TRevieweVo> result = baseMapper.selectPageList(pageQuery.build(), this.buildPageQuery(bo));
        result.getRecords().stream().forEach(it -> {
            String withdrawInfo = it.getWithdrawInfo();
            if (StringUtils.isNotBlank(it.getWithdrawInfo())) {
                List<WithdrawInfoVo> withdrawInfoVos = JsonUtils.parseArray(withdrawInfo, WithdrawInfoVo.class);
                if (!CollectionUtils.isEmpty(withdrawInfoVos)) {
                    it.setWithdrawInfoVo(withdrawInfoVos.stream().sorted(Comparator.comparing(WithdrawInfoVo::getCreateTime).reversed()
                    ).map(item -> {
                        return item.getCreateBy() + "--" + item.getCreateTime() + " 原因：" + item.getReason();
                    }).collect(Collectors.joining("</br>")));
                }
            }
        });
        return TableDataInfo.build(result);
    }

    /**
     * 撤回操作
     *
     * @param withdrawBo
     */
    @Override
    @Transactional
    public void withdrawOperator(WithdrawBo withdrawBo) {
        TRevieweInfo revieweInfo = new TRevieweInfo();
        Long id = withdrawBo.getId();
        // 保存撤回记录
        // 判断是否需要更新客户信息在审件记录 --- 拒绝也可以在撤回
        // 撤回记录信息
        String withdrawRemark = withdrawBo.getWithdrawRemark();
        if (!StringUtils.isNotBlank(withdrawRemark)) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("createBy", LoginHelper.getLoginUser().getNickName());
        map.put("createTime", DateUtils.getTime());
        map.put("reason", withdrawRemark);
        TRevieweInfoVo tRevieweInfoVo = baseMapper.selectVoById(id);
        String withdrawInfo = tRevieweInfoVo.getWithdrawInfo();
        if (StringUtils.isNotBlank(withdrawInfo)) {
            List<Map> maps1 = JsonUtils.parseArray(withdrawInfo, Map.class);
            maps1.add(map);
            revieweInfo.setWithdrawInfo(JsonUtils.toJsonString(maps1));
        } else {
            List reason = new ArrayList();
            reason.add(map);
            revieweInfo.setWithdrawInfo(JsonUtils.toJsonString(reason));
        }
        revieweInfo.setId(id);
        revieweInfo.setRevieweStatus(CustomerStatusEnum.YQY.getCode());
        baseMapper.updateById(revieweInfo);
        // 更新客户
        Long customerId = withdrawBo.getCustomerId();
        Customer customer = new Customer();
        customer.setId(customerId);
        customer.setCustomerStatus(CustomerStatusEnum.DQY.getCode());
        customer.setIsReviewe(id);
        customerMapper.updateById(customer);
    }

    private QueryWrapper<TRevieweVo> buildPageQuery(TRevieweBo bo) {
        QueryWrapper<TRevieweVo> mwq = Wrappers.query();
        mwq.eq("r.del_flag", "0");
        mwq.eq("tc.deleted", "0");
        mwq.apply("r.customer_id = tc.id");
        mwq.apply("r.dept_id = d.dept_id");
        mwq.apply("r.user_id = u.user_id");

        // 如果是业务员的话 只看自己创建的
        String leader = LoginHelper.getLoginUser().getLeader();
        if (Objects.equals("1", leader)) {
            mwq.apply("( d.ancestors like '" + LoginHelper.getLoginUser().getChildren() + "%'" + " OR " + " d.dept_id = "
                    + LoginHelper.getDeptId() + " OR " + "r.user_id = " + LoginHelper.getUserId() + " )");
        } else {
            mwq.apply(" r.user_id = " + LoginHelper.getUserId());
        }

        // 进件日期
        if (StringUtils.isNotBlank(bo.getApplyTimeScope())) {
            String dateStr = "";
            // 今天、昨天、最近7天
            if (Arrays.asList("0", "1", "7").contains(bo.getApplyTimeScope())) {
                dateStr = DateUtils.getTimeBeforeDay(DateUtils.getNowDate(),
                        Integer.parseInt(bo.getApplyTimeScope()), "before");
            }
            // 本月
            if (Objects.equals("30", bo.getApplyTimeScope())) {
                dateStr = DateUtils.getFirstDayOfMonth();
            }
            if (StringUtils.isNotBlank(dateStr)) {
                if (Arrays.asList("0", "1").contains(bo.getPkApplyTimeScope())) {
                    mwq.apply("r.in_time = DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                } else {
                    mwq.apply("r.in_time >= DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                }
            }
            // 自定义时间特殊处理
            if (Objects.equals("99", bo.getApplyTimeScope())) {
                mwq.ge(bo.getStartTime() != null, "r.in_time", bo.getStartTime());
                mwq.le(bo.getEndTime() != null, "r.in_time", bo.getEndTime());
            }
        }

        // 批款时间
        if (StringUtils.isNotBlank(bo.getPkApplyTimeScope())) {
            String dateStr = "";
            // 今天、昨天、最近7天
            if (Arrays.asList("0", "1", "7").contains(bo.getPkApplyTimeScope())) {
                dateStr = DateUtils.getTimeBeforeDay(DateUtils.getNowDate(),
                        Integer.parseInt(bo.getPkApplyTimeScope()), "before");
            }
            // 本月
            if (Objects.equals("30", bo.getPkApplyTimeScope())) {
                dateStr = DateUtils.getFirstDayOfMonth();
            }
            if (StringUtils.isNotBlank(dateStr)) {
                if (Arrays.asList("0", "1").contains(bo.getPkApplyTimeScope())) {
                    mwq.apply("r.approve_time = DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                } else {
                    mwq.apply("r.approve_time >= DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                }
            }
            // 自定义时间特殊处理
            if (Objects.equals("99", bo.getPkApplyTimeScope())) {
                mwq.ge(bo.getPkStartTime() != null, "r.approve_time", bo.getPkStartTime());
                mwq.le(bo.getPkEndTime() != null, "r.approve_time", bo.getPkEndTime());
            }
        }

        // 收款时间
        if (StringUtils.isNotBlank(bo.getSkApplyTimeScope())) {
            String dateStr = "";
            // 今天、昨天、最近7天
            if (Arrays.asList("0", "1", "7").contains(bo.getSkApplyTimeScope())) {
                dateStr = DateUtils.getTimeBeforeDay(DateUtils.getNowDate(),
                        Integer.parseInt(bo.getSkApplyTimeScope()), "before");
            }
            // 本月
            if (Objects.equals("30", bo.getSkApplyTimeScope())) {
                dateStr = DateUtils.getFirstDayOfMonth();
            }
            if (StringUtils.isNotBlank(dateStr)) {
                if (Arrays.asList("0", "1").contains(bo.getSkApplyTimeScope())) {
                    mwq.apply("r.payee_time = DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                } else {
                    mwq.apply("r.payee_time >= DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                }

            }
            // 自定义时间特殊处理
            if (Objects.equals("99", bo.getSkApplyTimeScope())) {
                mwq.ge(bo.getSkStartTime() != null, "r.payee_time", bo.getSkStartTime());
                mwq.le(bo.getSkEndTime() != null, "r.payee_time", bo.getSkEndTime());
            }
        }

        // 录入时间
        if (StringUtils.isNotBlank(bo.getLrApplyTimeScope())) {
            String dateStr = "";
            // 今天、昨天、最近7天
            if (Arrays.asList("0", "1", "7").contains(bo.getLrApplyTimeScope())) {
                dateStr = DateUtils.getTimeBeforeDay(DateUtils.getNowDate(),
                        Integer.parseInt(bo.getLrApplyTimeScope()), "before");
            }
            // 本月
            if (Objects.equals("30", bo.getLrApplyTimeScope())) {
                dateStr = DateUtils.getFirstDayOfMonth();
            }
            if (StringUtils.isNotBlank(dateStr)) {
                if (Arrays.asList("0", "1").contains(bo.getLrApplyTimeScope())) {
                    mwq.apply("DATE_FORMAT(r.create_time, '%Y-%m-%d 00:00:00' ) = DATE_FORMAT('" + dateStr
                            + "', '%Y-%m-%d 00:00:00' )");
                } else {
                    mwq.apply("DATE_FORMAT(r.create_time, '%Y-%m-%d 00:00:00' ) >= DATE_FORMAT('" + dateStr
                            + "', '%Y-%m-%d 00:00:00' )");
                }
            }
            // 自定义时间特殊处理
            if (Objects.equals("99", bo.getLrApplyTimeScope())) {
                mwq.ge(bo.getLrStartTime() != null, "r.create_time", bo.getLrStartTime());
                mwq.le(bo.getLrEndTime() != null, "r.create_time", bo.getLrEndTime());
            }
        }
        // 部门
        mwq.eq(bo.getDeptId() != null, "r.dept_id", bo.getDeptId());
        // 业务员
        mwq.like(StringUtils.isNotBlank(bo.getBusName()), "u.nick_name", bo.getBusName());
        // 客户姓名
        mwq.like(StringUtils.isNotBlank(bo.getCustomerName()), "tc.name", bo.getCustomerName());
//        mwq.eq(StringUtils.isNotBlank(bo.getName()), "tc.name", bo.getName());
        // 费率
        mwq.eq(bo.getFeerate() != null, "r.feerate", bo.getFeerate());
        // 进度就是客户状态
        mwq.eq(StringUtils.isNotBlank(bo.getRevieweStatus()), "r.reviewe_status", bo.getRevieweStatus());
        // 批款银行
        mwq.eq(StringUtils.isNotBlank(bo.getInBank()), "r.in_bank", bo.getInBank());
        mwq.eq(StringUtils.isNotBlank(bo.getBank()), "r.bank", bo.getBank());
        // 收款账户
        mwq.eq(StringUtils.isNotBlank(bo.getPayeeType()), "r.payee_type", bo.getPayeeType());

        mwq.eq(StringUtils.isNotBlank(bo.getSingletype()), "r.singletype", bo.getSingletype());
        // 来源
        mwq.like(StringUtils.isNotBlank(bo.getSource()), "tc.source", bo.getSource());
        // 9-- 已收款
        // 11-- 已放款
        // 13-- 审核通过 --进入到 放款、收款环节
        // 4--  待审核
        // 12-- 已拒绝
        mwq.last("\tORDER BY  \n" +
                "\t( case  r.reviewe_status \n" +
                "\twhen '4'  then '1' \n" +
                "\twhen '13' then '3' \n" +
                "\twhen '11' then '5' \n" +
                "\twhen '9'  then '7' \n" +
                "\twhen '12' then '9'\n" +
                "\tend ),r.in_time desc ");
        return mwq;
    }


    // 拉取客户
    @Override
    public TableDataInfo<CustomerVo> revieweInfoCustomerList(CustomerBo bo, PageQuery pageQuery) {
        Page<CustomerVo> result = baseMapper.revieweInfoCustomerList(pageQuery.build(), this.buildQuery(bo));
        return TableDataInfo.build(result.setRecords(regionBz(result)));
    }

    private QueryWrapper<CustomerVo> buildQuery(CustomerBo b) {
        QueryWrapper<CustomerVo> query = Wrappers.query();
        query.eq("tc.deleted", "0");
        query.like(StringUtils.isNotBlank(b.getName()), "tc.name", b.getName());
        query.eq(StringUtils.isNotBlank(b.getTel()), "tc.tel", b.getTel());
        query.eq(StringUtils.isNotBlank(b.getLevel()), "tc.level", b.getLevel());
        return query;
    }

    private List<CustomerVo> regionBz(Page<CustomerVo> result) {
        return result.getRecords().stream().peek(customerVo -> {
            String tel = customerVo.getTel();
            if (StringUtils.isNotBlank(tel)) {
                String resultTel = tel.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
                customerVo.setTel(resultTel);
            }
        }).collect(Collectors.toList());
    }


}
